package com.github.ghsea.sso.client.web;

import com.github.ghsea.sso.client.common.SpringContext;
import com.github.ghsea.sso.client.security.cas.UserInfoUtils;
import java.io.IOException;
import java.util.Optional;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.session.Session;

/**
 * 简单登录状态。从Request中拿sso的cookie去验证用户是否已登录。
 *
 * @author guhai
 */
public abstract class LoginStatusFilter implements Filter {

    private UserInfoUtils userInfoUtils;

    @Override
    public void init(FilterConfig filterConfig) {
        userInfoUtils = SpringContext.getBean(UserInfoUtils.class);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Optional<Session> sessionOptional = userInfoUtils.getSession((HttpServletRequest) servletRequest);
        if (!sessionOptional.isPresent()) {
            writeNotLoginResponse((HttpServletResponse) servletResponse);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

    protected abstract void writeNotLoginResponse(final HttpServletResponse response);

}
